/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pe.com.procesos;

import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import pe.com.ColaProcesamiento;
import pe.com.ColaUnidadesSinProcesar;
import pe.com.unidades.Chip;
import pe.com.util.HtmlUnitDriver2;

/**
 *
 * @author romulogalindo
 */
public class ProcesarAsterisk extends Proceso {

    WebDriver driver;
    boolean process = true;

    public ProcesarAsterisk() {
        DesiredCapabilities capabilities = DesiredCapabilities.firefox();
        capabilities.setBrowserName("Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0");
        capabilities.setVersion("24.0");
        capabilities.setJavascriptEnabled(true);

        driver = new HtmlUnitDriver2(capabilities);
        driver.get("http://www.miclaro.com.pe");

        java.util.Iterator<Cookie> it_cookie = driver.manage().getCookies().iterator();
        Cookie sesion = null;
        while (it_cookie.hasNext()) {
            Cookie cookie = it_cookie.next();
            if (cookie.getName().contentEquals("JSESSIONID")) {
                sesion = cookie;
                break;
            }
        }
        driver.manage().deleteCookie(sesion);
        logearnos(driver);
//        System.out.println("Ya nos hemos logeado");
    }

    public void procesar() {
//        System.out.println("A punto de procesar [" + process + "]");
        try {
            while (process) {
//                Object obj = ColaUnidadesSinProcesar.consumirUnidad();
                Object obj = ColaUnidadesSinProcesar.consumirUnidad2();

                if (obj != null) {
                    if (obj instanceof Chip) {
                        Chip chip = (Chip) obj;
//                        System.out.println("Dato conseguido... " + chip.getNu_chip());
                        procesar(chip);
                        if (!chip.isIl_process()) {
                            System.out.println("Reintentando:"+chip.getNu_chip());
                            ColaUnidadesSinProcesar.nuevaUnidad(chip);
                        } else {
                            ColaProcesamiento.nuevoProceso(chip);
                        }
                    } else {
//                        System.out.println("El objeto obtenido es nulo.");
                        //deteniendo
                        process = false;
                    }
                } else {
//                    System.out.println("El objeto obtenido es nulo.");
                    //deteniendo
                    process = false;
                }
            }
        } catch (Exception ep) {
            System.out.println("Ep:" + ep.getMessage());
        }
    }

    public void procesar(Chip chip) {
//        System.out.println("Dirigiendo al consumo tope");
        driver.get("http://www.miclaro.com.pe/wps/myportal/claromovil/sitioweb/operaciones/topesconsumoindividual");
        WebElement fs2 = null;
        try {
            fs2 = (new WebDriverWait(driver, 10)).until(new ExpectedCondition<WebElement>() {
                public WebElement apply(WebDriver d) {
                    return d.findElement(By.id("ns_Z7_NU4O8B1A084O20IVUPP5SV2882_numeroInput"));
                }
            });
        } catch (Exception ep) {
        }
//        System.out.println("=========================================================================");
//        System.out.println("" + driver.getPageSource());
//        System.out.println("=========================================================================");
//        System.out.println("poniendo el numero a consultar..." + chip.getNu_chip());
        boolean il_plan = false;
        for (int i = 0; i < 5; i++) {
            ((JavascriptExecutor) driver).executeScript("document.getElementById(\"ns_Z7_NU4O8B1A084O20IVUPP5SV2882_numeroInput\").value='" + chip.getNu_chip() + "'");
            driver.findElement(By.id("ns_Z7_NU4O8B1A084O20IVUPP5SV2882_consultarButton")).click();

            try {
                fs2 = (new WebDriverWait(driver, 10)).until(new ExpectedCondition<WebElement>() {
                    public WebElement apply(WebDriver d) {
                        return d.findElement(By.id("ns_Z7_NU4O8B1A084O20IVUPP5SV2882_planSelect"));
                    }
                });
                il_plan = true;
                i = 5;
            } catch (Exception ep) {
                il_plan = false;
            }
        }

        if (!il_plan) {
            System.out.println("======================================");
            System.out.println("Número:" + chip.getNu_chip() + " Error al procesar datos..");
            System.out.println("======================================");
//                break;
        } else {
            boolean bolsa = false;
            ((JavascriptExecutor) driver).executeScript("document.getElementById(\"ns_Z7_NU4O8B1A084O20IVUPP5SV2882_planSelect\").value='Claro Bolsa CDI'");
            ((JavascriptExecutor) driver).executeScript("document.getElementById(\"ns_Z7_NU4O8B1A084O20IVUPP5SV2882_operacion\").value='consultarBolsa'");
            ((JavascriptExecutor) driver).executeScript("document.getElementById(\"ns_Z7_NU4O8B1A084O20IVUPP5SV2882_topesConsumoForm\").setAttribute('action','/wps/myportal/claromovil/sitioweb/operaciones/topesconsumoindividual/!ut/p/b1/lc_LDoIwEAXQb_ELZlpLKUs0EFCkJDy03RhMDBKBbozfb3Hl-zG7Sc5N7gUNihDiUY8zgrABPdTntqlPrRnqbvw136Ylk2JGfBRMUoyrMsucvKJYuhaoWyCXxQiCyo2TCHlC_83nU8eClQwSxhDn_Lc8vjkfv-UXoJvO7OzUNeh7_GLLA3guewUf2qSR6fegLHPftRKCQgEqhF53YSiObXYwkwtaW_Qz/dl4/d5/L2dBISEvZ0FBIS9nQSEh/pw/Z7_NU4O8B1A084O20IVUPP5SV2882/ren/p=accion=consultar/-/')");

            driver.findElement(By.id("ns_Z7_NU4O8B1A084O20IVUPP5SV2882_topesConsumoForm")).submit();

            try {
                fs2 = (new WebDriverWait(driver, 10)).until(new ExpectedCondition<WebElement>() {
                    public WebElement apply(WebDriver d) {
                        return d.findElement(By.id("ns_Z7_NU4O8B1A084O20IVUPP5SV2882_planSelect"));
                    }
                });
                //si todo saliio bien parte 1
                WebElement comboBox = driver.findElement(By.id("ns_Z7_NU4O8B1A084O20IVUPP5SV2882_planSelect"));
                org.openqa.selenium.support.ui.Select selectedValue = new org.openqa.selenium.support.ui.Select(comboBox);
                String val = selectedValue.getFirstSelectedOption().getAttribute("value");
//                    System.out.println("Comprando si esta selecionado");
                if (val.contentEquals("Claro Bolsa CDI")) {
                    //todo salio bien!
//                        i = 5;
                    bolsa = true;
                }
            } catch (Exception ep) {
                //se volvera a intentar
                bolsa = false;
            }

            if (bolsa) {
                boolean plan = false;
                //cdatos del plan
                ((JavascriptExecutor) driver).executeScript("document.getElementById(\"ns_Z7_NU4O8B1A084O20IVUPP5SV2882_bolsaSelect\").value='Bolsa de Soles o Minutos Asignados al Plan'");
                ((JavascriptExecutor) driver).executeScript("document.getElementById(\"ns_Z7_NU4O8B1A084O20IVUPP5SV2882_operacion\").value='consultarLinea'");
                ((JavascriptExecutor) driver).executeScript("document.getElementById(\"ns_Z7_NU4O8B1A084O20IVUPP5SV2882_topesConsumoForm\").setAttribute('action','/wps/myportal/claromovil/sitioweb/operaciones/topesconsumoindividual/!ut/p/b1/lc_LDoIwEAXQb_ELZlpLKUs0EFCkJDy03RhMDBKBbozfb3Hl-zG7Sc5N7gUNihDiUY8zgrABPdTntqlPrRnqbvw136Ylk2JGfBRMUoyrMsucvKJYuhaoWyCXxQiCyo2TCHlC_83nU8eClQwSxhDn_Lc8vjkfv-UXoJvO7OzUNeh7_GLLA3guewUf2qSR6fegLHPftRKCQgEqhF53YSiObXYwkwtaW_Qz/dl4/d5/L2dBISEvZ0FBIS9nQSEh/pw/Z7_NU4O8B1A084O20IVUPP5SV2882/ren/p=accion=consultar/-/')");
                driver.findElement(By.id("ns_Z7_NU4O8B1A084O20IVUPP5SV2882_topesConsumoForm")).submit();
                try {
                    fs2 = (new WebDriverWait(driver, 10)).until(new ExpectedCondition<WebElement>() {
                        public WebElement apply(WebDriver d) {
                            return d.findElement(By.id("ns_Z7_NU4O8B1A084O20IVUPP5SV2882_bolsaSelect"));
                        }
                    });
                    //si todo saliio bien parte 1
                    WebElement comboBox = driver.findElement(By.id("ns_Z7_NU4O8B1A084O20IVUPP5SV2882_bolsaSelect"));
                    org.openqa.selenium.support.ui.Select selectedValue = new org.openqa.selenium.support.ui.Select(comboBox);
                    String val = selectedValue.getFirstSelectedOption().getAttribute("value");
//                        System.out.println("Comprando si esta selecionado el plan");
                    if (val.contentEquals("Bolsa de Soles o Minutos Asignados al Plan")) {
                        //todo salio bien!
                        plan = true;
                    }
                } catch (Exception ep) {
                    plan = false;
                }

                if (plan) {

                    try {
                        String total = driver.findElements(By.className("formularioTableTC")).get(0).findElements(By.className("formularioTableBorderPlomoTopes")).get(0).findElements(By.className("miClaroTr")).get(1).findElements(By.tagName("TD")).get(1).getText().trim().replace("Minutos", "").trim();
                        String base = driver.findElements(By.className("formularioTableTC")).get(0).findElements(By.className("formularioTableBorderPlomoTopes")).get(0).findElements(By.className("miClaroTr")).get(2).findElements(By.tagName("TD")).get(1).getText().trim().replace("Minutos", "").trim();
                        String util = driver.findElements(By.className("formularioTableTC")).get(0).findElements(By.className("formularioTableBorderPlomoTopes")).get(0).findElements(By.className("miClaroTr")).get(2).findElements(By.tagName("TD")).get(3).getText().trim().replace("Minutos", "").trim();

//                System.out.println("======================================");
                        chip.setCa_minasi(Double.parseDouble(base));
                        chip.setCa_mincon(Double.parseDouble(util));
                        chip.setIl_process(true);
//                System.out.println("======================================");
//                System.out.println("Número:" + numero + " Total: " + total + " min ,asignado:" + base + " min, utilizado:" + util + " min. ");
                    } catch (Exception ep) {
                        chip.setIl_process(false);
//                System.out.println("======================================");
//                System.out.println("Número:" + chip.getNu_chip() + " Error al procesar datos..");
//                System.out.println("======================================");
                    }
                }
            }
        }

    }

    public void logearnos(WebDriver driver) {
        boolean logeado = false;
        String usuario = "989280977";
        String password = "715383";

        ((JavascriptExecutor) driver).executeScript("document.getElementById(\"ns_Z7_NU4O8B1A0OEL30IVPSI0US3081_loginP\").value='" + usuario + "'");
        ((JavascriptExecutor) driver).executeScript("document.getElementById(\"personas_p\").value='" + password + "'");
        ((JavascriptExecutor) driver).executeScript("document.getElementById(\"ns_Z7_NU4O8B1A0OEL30IVPSI0US3081_clave\").value='     '");
        driver.findElement(By.id("ns_Z7_NU4O8B1A0OEL30IVPSI0US3081_btnIngresar")).click();
        WebElement fs = null;
        try {
            fs = (new WebDriverWait(driver, 8)).until(new ExpectedCondition<WebElement>() {
                public WebElement apply(WebDriver d) {
                    return d.findElement(By.id("bannerNav"));
                }
            });
        } catch (Exception ep) {
            fs = null;
            logeado = true;
        }
//        return logeado;
    }

}
